// eslint-disable-next-line import/no-extraneous-dependencies
import { Request, Response } from 'express';
import { parse } from 'url';
import mockjs from 'mockjs';
import { RoleTableListItem, RoleTableListParams } from '@/pages/ums/role/roleData';

// mock tableListDataSource
const genList = () => {
    const tableListDataSource: RoleTableListItem[] = mockjs.mock({
        'list|100': [{
            roleId: /\d{5,10}/,
            roleName: '@word',
            description: '@word',
            status: '@integer(0,1)',
            deleteStatus: '@integer(0,1)',
            createTime: '@datetime',
            creator: '@word',
            updateTime: '@datetime',
            modifier: '@word',
        }],
    }).list;
    return tableListDataSource;
};

let tableListDataSource = genList();

/**
 * 查询列表角色
 */
function queryRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { current = 1, pageSize = 10 } = req.query;
    const params = (parse(realUrl, true).query as unknown) as RoleTableListParams;

    let dataSource = [...tableListDataSource].slice(
        ((current as number) - 1) * (pageSize as number),
        (current as number) * (pageSize as number),
    );
    if(params.sorter){
        const sorter = JSON.parse(params.sorter as any);
    if (sorter) {
        dataSource = dataSource.sort((prev, next) => {
            let sortNumber = 0;
            Object.keys(sorter).forEach((key) => {
                if (sorter[key] === 'descend') {
                    if (prev[key] - next[key] > 0) {
                        sortNumber += -1;
                    } else {
                        sortNumber += 1;
                    }
                    return;
                }
                if (prev[key] - next[key] > 0) {
                    sortNumber += 1;
                } else {
                    sortNumber += -1;
                }
            });
            return sortNumber;
        });
    }
    }
    if (params.filter) {
        const filter = JSON.parse(params.filter as any) as {
            [key: string]: string[];
        };
        if (Object.keys(filter).length > 0) {
            dataSource = dataSource.filter((item) => {
                return Object.keys(filter).some((key) => {
                    if (!filter[key]) {
                        return true;
                    }
                    if (filter[key].includes(`${item[key]}`)) {
                        return true;
                    }
                    return false;
                });
            });
        }
    }

    const result = {
        data: dataSource,
        total: tableListDataSource.length,
        success: true,
        pageSize,
        current: parseInt(`${params.currentPage}`, 10) || 1,
    };

    return res.json(result);
}

/**
 * 获取角色
 */
function getRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    let data;
    if(id){
        data = tableListDataSource.find((item) => item.roleId && item.roleId.toString()===id.toString());
    }

    const result = {
        data,
        success: true,
    };

    return res.json(result);
}

/**
 * 新增角色
 */
function addRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const data = req.body as RoleTableListItem;
        data.roleId = mockjs.mock(/\d{5,10}/);

    if(data){
        tableListDataSource.splice(0,0,data);
    }

    const result = {
        success: true,
    };
    return res.json(result);
}

/**
 * 更新角色
 */
function updateRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    const params = req.body as RoleTableListItem;
    if(id && params){
        const data: RoleTableListItem|undefined = tableListDataSource.find((item) => item.roleId && item.roleId.toString()===id.toString());
        if(data){
            Object.assign(
                data,
                params
            )
        }
    }

    const result = {
        success: true,
    };
    return res.json(result);

}

/**
 * 删除角色
 */
function deleteRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { id } = req.params;
    tableListDataSource = tableListDataSource.filter((item)=>item.roleId!==id);

    const result = {
        success: true,
    };

    return res.json(result);
}

/**
 * 批量删除角色
 */
function batchDeleteRole(req: Request, res: Response, u: string) {
    let realUrl = u;
    if (!realUrl || Object.prototype.toString.call(realUrl) !== '[object String]') {
        realUrl = req.url;
    }
    const { ids } = req.body;
    if(ids && ids.length){
        tableListDataSource = tableListDataSource.filter((item)=>
            item.roleId && ids.indexOf(item.roleId)===-1
        );
    }

    const result = {
        success: true,
    };

    return res.json(result);
}
/**
 * 更新角色权限
 */
function updateRolePermissions(req: Request, res: Response) {
    const result = {
        success: true,
    };

    return res.json(result);
}
/**
 * 获取角色权限勾选项
 */
function getRolePermissionSelected(req: Request, res: Response) {
    const result = {
        success: true,
        data: [],
    };

    return res.json(result);
}


export default {
    'GET /api/ums/role': queryRole,
    'GET /api/ums/role/:id': getRole,
    'POST /api/ums/role': addRole,
    'POST /api/ums/role/permissions/relation': updateRolePermissions,
    'PUT /api/ums/role/:id': updateRole,
    'DELETE /api/ums/role/:id': deleteRole,
    'DELETE /api/ums/role': batchDeleteRole,
    'GET /api/ums/role/permission/checkedItems': getRolePermissionSelected,
};
